package com.hs.hlw.credit.system.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * FileUtil
 * @author zhb
 * @date 2018/08/16
 */
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    public static boolean saveFile(String fileName, InputStream in) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(fileName));
            byte[] temp = new byte[1024];
            int i = in.read(temp);
            while (i != -1) {
                fos.write(temp, 0, temp.length);
                fos.flush();
                i = in.read(temp);
            }
            return true;
        } catch (Exception e) {
            LOGGER.error("文件保存失败", e);
            return false;
        } finally {
            close(in);
            close(fos);
        }
    }

    /**
     * 关闭输入流
     * @param in
     */
    public static void close(InputStream in) {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            // TODO
        }
    }

    /**
     * 关闭输出流
     * @param out
     */
    public static void close(OutputStream out) {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            // TODO
        }
    }

    /**
     * 创建目录
     * @param dir
     * @return
     */
    public static boolean mkdirs(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            return file.mkdirs();
        } else {
            return true;
        }
    }
}
